import sys
import person_parser
import getopt
import urllib
import StringIO
import urlparse
import httplib
import socket
import logging

def PrintUsageExit(num):
   print "example: cmd --url=http://localhost:8080/load --filename=name --batch_size=100"
   sys.exit(num)

def ParseArguments(argv):
  opts, args = getopt.getopt(
    argv[1:],
    'h',
    ['help',
     'url=',
     'filename=',
     'batch_size=',
    ])

  url = None
  filename = None
  batch_size = 100

  for option, value in opts:
    if option in ('-h', '--help'):
      PrintUsageExit(0)
    if option == '--url':
      url = value
    if option == '--filename':
      filename = value
    if option == '--batch_size':
      batch_size = int(value)
      if batch_size <= 0:
        print >>sys.stderr, 'batch_size must be 1 or larger'
        PrintUsageExit(1)
  if not (url and filename and batch_size) :
    PrintUsageExit(1)
  return(url, filename, batch_size)

# We encode a person object as "key,value,key,value..."
def UrlEncode(person):
  values = []
  for key,value in person.__dict__.items():
    if key and value:
      values.append(key)
      values.append(value)
  return urllib.quote_plus(",".join(values))
  
def PostContent(url, content):
  scheme, host_port, path, query, fragment = urlparse.urlsplit(url)
  host_port, path

  logging.info('Connecting to %s', host_port)
  try:
    headers = {
      'Content-Type': 'text/plain',
      'Content-Length': len(content),
    }

    connection = httplib.HTTPConnection(host_port)
    try:
      connection.request('POST', path, content, headers)
      response = connection.getresponse()
      status = response.status
      reason = response.reason
      content = response.read()
      logging.debug('Received response code %d: %s', status, reason)
      if status != httplib.OK:
        raise Exception('Received code %d: %s\n%s' % ( status, reason, content))
    finally:
      connection.close()
  except (IOError, httplib.HTTPException, socket.error), e:
    logging.error('Encountered exception accessing HTTP server: %s', e)
    raise Exception(e)

def main():
  url, filename, batch_size = ParseArguments(sys.argv)
  persons = person_parser.ParsePersonsFromFile(filename)

  length = len(persons)
  start = 0
  count = 0
  # Send requests in batch
  for start in range(0, len(persons), batch_size):
    buffer = StringIO.StringIO()
    for p in persons[start : start + batch_size]:
      buffer.write(UrlEncode(p))
      buffer.write(" ")
    PostContent(url, buffer.getvalue())
    buffer.close()
    count += batch_size
    logging.error("Processed % entries ..." % count)

if __name__ == "__main__":
    main()    
